package com.dks.util;


import java.io.File;
import java.io.IOException;

import com.dks.exception.BaseException;
import com.dks.result.ResultInfo;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.UploadManager;
import com.qiniu.util.Auth;

import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


/**
 * @Author: Ah Nan
 * @Description: 七牛云上传图片
 * @Date: 15:53 2020/4/22
 * @Modificd By:
 * @Param:
 * @return:
 * @throw: 请描述异常信息
 */
public class QiniuCloudUtil {

    // 密钥
    private static final Auth auth = Auth.create(Commond.QN_ACCESS_KEY, Commond.QN_SECRET_KEY);

    //上传
    public static String upload(File file, String key) throws IOException, BaseException {
        // 创建上传对象，Zone*代表地区
//            Configuration configuration = new Configuration(Zone.zone2());

        UploadManager uploadManager = new UploadManager();
        try {
            // 调用put方法上传
            String token = auth.uploadToken(Commond.AWS_BUCKET_NAME);
            if (StringUtils.isEmpty(token)) {
                System.out.println("未获取到token，请重试！");
                return null;
            }
            System.out.println("File name = " + file.getName());
            Response res = uploadManager.put(file, key, token);
            //上传后删除file
            file.delete();
            // 打印返回的信息
            if (res.isOK()) {
                return "http://http://image.decary.tech/" + key;
            }
        } catch (QiniuException e) {
            Response r = e.response;
            // 请求失败时打印的异常的信息
            e.printStackTrace();
            System.out.println("error " + r.toString());
            throw new BaseException(ResultInfo.EXCEPTION);

        }
        return null;
    }


    /**
     * @param file 原文件类型
     * @return File
     * @throws IOException
     * @Author: Ah Nan
     * MultipartFile 转换成File
     */
    public File convertMultipartFile(MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename().replaceAll("\\?", "1");
        File newFile = new File(filename);
        file.transferTo(newFile.getAbsoluteFile());
        return newFile;
    }

}
